/**
 * @Description: 封装购物车模块
 * @Author: yxm
 * @Date: 2023-11-27
 */
import {defineStore} from "pinia";
import {ref, computed} from 'vue'
export const useCartStore = defineStore('cart', () =>{
    //1. 定义state = cartList
    const cartList = ref([])
    //2. 定义action
    const addCart = (goods) => {
        const item = cartList.value.find((item) => goods.skuId === item.skuId)
        if (item) {
            // 找到了
            item.count++   //这里好像有BUG， 应该加的是goods的count数
        } else {
            // 没找到
            cartList.value.push(goods)
        }
    }
    const delCart = (skuId) => {
        const idx = cartList.value.findIndex( (item) => skuId === item.skuId)
        cartList.value.splice(idx, 1)
    }
    
    // 单选功能
    const singleCheck = (skuId, selected) => {
        // 通过skuId找到要修改的那一项 然后把它的selected修改为传过来的selected
        const item = cartList.value.find((item) => item.skuId === skuId)
        item.selected = selected
    }
    
    const allCount = computed( () => cartList.value.reduce( (a,c) => a + c.count, 0))
    const allPrice = computed( () => cartList.value.reduce( (a,c) => a + c.count * c.price,0))
    
    // 是否全选计算属性
    const isAll = computed(() => cartList.value.every((item) => item.selected))
    
    // 全选功能action
    const allCheck = (selected) => {
        // 把cartList中的每一项的selected都设置为当前的全选框状态
        cartList.value.forEach(item => item.selected = selected)
    }
    
    return {
        cartList,
        addCart,
        delCart,
        singleCheck,
        isAll,
        allCount,
        allPrice,
        allCheck
    }
}, {persist: true})